/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eightbears.beboy.ui.merchant.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.SearchAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.EditDataDialog;
import com.eightbears.beboy.entity.SearchUser;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.DemoHelper;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.adapter.EaseContactAdapter;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.widget.EaseSidebar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CHAT_ROBOT;
import static com.eightbears.beboy.base.util.CommonAPI.CHAT_ROOM;
import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.GROUP_USERNAME;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.NEW_FRIENDS_USERNAME;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_PAGE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_SEARCH;
import static com.eightbears.beboy.base.util.CommonAPI.URL_UPDATEMANAGER;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;


public class PickManagerContactsActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    public static final String EVENT_ADD_MANAGER = "EVENT_ADD_MANAGER";


    /**
     * if this is a new group
     */
    protected boolean isCreatingNewGroup;
    private PickContactAdapter contactAdapter;
    /**
     * members already in the group
     */
    private List<String> existMembers;
    private List<String> joinMembers;
    private String mParams_add;
    private EditText mQuery;
    private ListView mListView;
    private String searchKey;
    private int page = 1;
    private RelativeLayout mRl_friend_list;
    private View mView_friend_list;
    private SearchAdapter mSearchAdapter;
    private SwipeBackLayout sw_finish;


    private boolean isErr = true;
    private int isEnd = 0;
    private RecyclerView mRv_list;
    private SwipeRefreshLayout mSwipeLayout;
    private EditDataDialog editDataDialog;
    private String mUser_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_manager_pick_contacts);
        initView();
        initData();
        initEvent();
    }

    protected void initData() {
        // get contact list
        List<EaseUser> alluserList = new ArrayList<>();
        for (EaseUser user : DemoHelper.getInstance().getContactList().values()) {
            if (!user.getUsername().equals(NEW_FRIENDS_USERNAME) &
                    !user.getUsername().equals(GROUP_USERNAME) &
                    !user.getUsername().equals(CHAT_ROOM) &
                    !user.getUsername().equals(CHAT_ROBOT))

                if (Integer.parseInt(user.getUsername()) > 100) {
                    alluserList.add(user);
                }

        }
        // sort the list
        Collections.sort(alluserList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });

        contactAdapter = new PickContactAdapter(this, R.layout.em_row_contact_with_checkbox, alluserList);
        mListView.setAdapter(contactAdapter);
        mSearchAdapter = new SearchAdapter();
        mSearchAdapter.openLoadAnimation();
        mSearchAdapter.setOnLoadMoreListener(this);
        mSearchAdapter.putEventBtnName("任命经理");
        mRv_list.setAdapter(mSearchAdapter);

    }

    protected void initEvent() {
        mSearchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SearchUser.DataBean user = (SearchUser.DataBean) adapter.getData().get(position);
                mUser_id = user.getUser_id();
                editDataDialog.show();
            }
        });
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox checkBox = (CheckBox) view.findViewById(com.eightbears.beboy.R.id.checkbox);
                checkBox.toggle();
            }
        });

        mQuery.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    mRl_friend_list.setVisibility(View.GONE);
                    mView_friend_list.setVisibility(View.VISIBLE);
                    searchKey = s.toString();
                    findFriend();
                } else {
                    mRl_friend_list.setVisibility(View.VISIBLE);
                    mView_friend_list.setVisibility(View.GONE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
        });

        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    protected void initView() {
        initEditDialog();
        mListView = (ListView) findViewById(R.id.list);
        mRl_friend_list = (RelativeLayout) findViewById(R.id.rl_friend_list);
        mView_friend_list = findViewById(R.id.view_friend_list);
        mRv_list = (RecyclerView) findViewById(R.id.rv_list);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
        sw_finish = (SwipeBackLayout) findViewById(R.id.sw_finish);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        mSwipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));

        mRv_list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        String groupId = getIntent().getStringExtra("groupId");
        mParams_add = "1";
        mQuery = (EditText) findViewById(R.id.query);
        if (mParams_add != null) {
            findViewById(R.id.btn_group_pick_ok).setVisibility(View.GONE);
            findViewById(R.id.search_bar_view).setVisibility(View.VISIBLE);
        }
        if (groupId == null) {// create new group
            isCreatingNewGroup = true;
            existMembers = (List<String>) getIntent().getSerializableExtra("members");
            joinMembers = existMembers;
        } else {
            // get members of the group
            EMGroup group = EMClient.getInstance().groupManager().getGroup(groupId);
            existMembers = group.getMembers();
        }

        if (existMembers == null)
            existMembers = new ArrayList<>();


        ((EaseSidebar) findViewById(com.eightbears.beboy.R.id.sidebar)).setListView(mListView);
    }

    private void initEditDialog() {
        editDataDialog = new EditDataDialog(this);
        editDataDialog.setTitleText(getString(R.string.text_add_manager_title));
        editDataDialog.setEditHintText(getString(R.string.hint_manager_nickname));
        editDataDialog.setOnItemClickListener(new EditDataDialog.DialogEditNameListener() {
            @Override
            public void onSetDialogNumOneListener(View v, String name) {
                switch (v.getId()) {
                    case R.id.btn_cancel:
                        editDataDialog.dismiss();
                        break;
                    case R.id.btn_editdialog_ensure:
                        if (!TextUtils.isEmpty(name))
                             getData(name);
                        else  ShowToast.showShortToast(getString(R.string.alert_input_empty));
                        editDataDialog.dismiss();
                        break;
                }
            }
        });

    }

    /**
     * save selected members
     *
     * @param v
     */
    public void save(View v) {
        List<String> var = getToBeAddMembers();
        if (null != joinMembers && joinMembers.size() > 0) {
            var.addAll(joinMembers);
        }
        setResult(RESULT_OK, new Intent().putExtra("newmembers", var.toArray(new String[var.size()])));
        finish();
    }

    /**
     * get selected members
     *
     * @return 成员
     */
    private List<String> getToBeAddMembers() {
        List<String> members = new ArrayList<String>();
        int length = contactAdapter.isCheckedArray.length;
        for (int i = 0; i < length; i++) {
            String username = contactAdapter.getItem(i).getUsername();
            if (contactAdapter.isCheckedArray[i] && !existMembers.contains(username)) {
                members.add(username);
            }
        }
        return members;
    }

    /**
     * adapter
     */
    private class PickContactAdapter extends EaseContactAdapter {

        private boolean[] isCheckedArray;
        private List<EaseUser> users;

        public PickContactAdapter(Context context, int resource, List<EaseUser> users) {
            super(context, resource, users);
            isCheckedArray = new boolean[users.size()];
            this.users = users;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);

            final String username = getItem(position).getUsername();

            final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
            ImageView avatarView = (ImageView) view.findViewById(com.eightbears.beboy.R.id.avatar);
            TextView nameView = (TextView) view.findViewById(com.eightbears.beboy.R.id.name);


            if (users.size() > 0 && mParams_add != null) {
                checkBox.setVisibility(View.INVISIBLE);
            }

            if (checkBox != null) {
                if (existMembers != null && existMembers.contains(username)) {
                    checkBox.setButtonDrawable(com.eightbears.beboy.R.drawable.em_checkbox_bg_gray_selector);
                } else {
                    checkBox.setButtonDrawable(com.eightbears.beboy.R.drawable.em_checkbox_bg_selector);
                }

                checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // check the exist members
                        if (mParams_add != null) {
                            mUser_id = FriendsCache.getInstance(getContext()).getCacheByName(users.get(position).getNickname()).getUser_id();
                            editDataDialog.show();
                        } else {
                            if (existMembers.contains(username)) {
                                isChecked = true;
                                checkBox.setChecked(true);
                            }
                            isCheckedArray[position] = isChecked;
                        }
                    }
                });
                // keep exist members checked
                if (existMembers.contains(username)) {
                    checkBox.setChecked(true);
                    isCheckedArray[position] = true;
                } else {
                    checkBox.setChecked(isCheckedArray[position]);
                }
            }

            return view;
        }
    }

    public void back(View view) {
        finish();
    }

    /**
     * 修改
     */
    private void getData(String name) {
        PostFormBuilder builder = OkHttpUtils.post();//创建请求构建器
        builder.url(URL_UPDATEMANAGER);
        builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builder.addParams("name", name);
        builder.addParams("id", mUser_id);
        builder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                try {
                    EventBus.getDefault().post(EVENT_ADD_MANAGER);
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if(e.getMessage().contains("40001")){
                    ShowToast.showShortToast(getString(R.string.text_alread_manager));
                    return;
                }
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PickManagerContactsActivity.this, status_error);
            }
        });
    }


    /**
     * 查找好友
     */
    private void findFriend() {
        OkHttpUtils.get().url(URL_RESET_SEARCH)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", "1").addParams("keyword", searchKey)
                .addParams(PARAM_URL_PAGE, String.valueOf(page))
                .addParams(PARAM_URL_SIZE, PARAMS_PAGE_SIZE)
                .addParams("no_need_friends", "1")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                mSwipeLayout.setRefreshing(false);
                SearchUser searchUser = GsonUtil.fromJson(response, SearchUser.class);
                if (searchUser.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    isEnd = Integer.parseInt(searchUser.getData().getIs_end());
                    if (page == 1)
                        mSearchAdapter.setNewData(searchUser.getData().getList());
                    else {
                        mSearchAdapter.addData(searchUser.getData().getList());
                        mSearchAdapter.loadMoreComplete();
                    }

                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PickManagerContactsActivity.this, status_error);
            }
        });
    }


    @Override
    public void onRefresh() {
        mSearchAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mSearchAdapter.getData().clear();
                findFriend();
                mSearchAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    mSearchAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        findFriend();
                    } else {
                        isErr = true;
                        Toast.makeText(getApplication(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        mSearchAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
}
